﻿using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.Client.Implementation
{
    /// <summary>
    /// Returns all configured connection strings as <see cref="IConnectionInfo"/> instances.
    /// </summary>
    [Implements(typeof(IConnectionInfoProvider))]
    public class ConnectionInfoProvider : IConnectionInfoProvider
    {
        #region IConnectionInfoProvider Members

        /// <summary>
        /// Returns a list of <see cref="IConnectionInfo"/> instances that describes the 
        /// connections available to the client.
        /// </summary>
        /// <returns>An <see cref="IEnumerable{T}"/> instance that containing available <see cref="IConnectionInfo"/> instances.</returns>
        public IEnumerable<IConnectionInfo> GetConnections()
        {
            var connections = from setting in ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>()
                              select
                                  new ConnectionInfo()
                                      {
                                          ConnectionString = setting.ConnectionString,
                                          Name = setting.Name.Split(new[] { '.' }).Last(),
                                          ProviderName = setting.ProviderName
                                      };
            return connections.Cast<IConnectionInfo>();
        }

        #endregion
    }
}
